import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { FormRulesExt } from '#/api';

import { computed } from 'vue';

import { sendEmailCode, UserApi } from '#/api';
import { MsgTemplateCodeEnum } from '#/enums/commonEnum';
import useCountDown from '#/hooks/core/useCountDown';
import useLoad from '#/hooks/core/useLoad';
import { useMessage } from '#/hooks/web/useMessage';

export function useCaptcha(formRef: Ref) {
  const { createMessage } = useMessage();

  const { loading, startLoading, endLoading } = useLoad();
  const { currentCount, start, isStart } = useCountDown(60);

  const label = computed(() => {
    let text = '获取验证码';

    const countingLabel = `${currentCount.value}秒后重新获取`;

    if (loading.value) {
      text = '';
    }

    if (isStart.value) {
      text = countingLabel;
    }

    return text;
  });

  async function getCaptcha(value: string) {
    if (loading.value) {
      return;
    }

    await formRef.value?.getFormRef().validateFields('email');
    if (!value) {
      createMessage.warning('请填写邮箱');
      return;
    }

    startLoading();

    try {
      await sendEmailCode(value, MsgTemplateCodeEnum.EMAIL_EDIT);
      createMessage.success?.('发送成功');

      start();
    } catch (error: any) {
      createMessage.warning(error?.msg || '发送失败');
    } finally {
      endLoading();
    }
  }

  return {
    label,
    start,
    stop,
    isStart,
    loading,
    getCaptcha,
  };
}

export function createCrudOptions(
  _props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  return {
    crudOptions: {
      request: { addRequest: UserApi.updateEmailRequest },
      form: { mode: 'add', col: { span: 24 } },
      columns: {
        id: {
          title: 'ID',
          type: 'text',
          form: { show: false },
        },
        templateCode: {
          title: '消息模板',
          form: { show: false },
          type: 'text',
        },
        email: {
          title: '新邮箱',
          type: 'text',
        },
        code: {
          title: '验证码',
          type: 'text',
        },
      },
    },
  };
}

export const frontRules = (_: Ref): FormRulesExt => {
  return {};
};
